﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using My.Common.EntityHelper;


namespace My.Common.Helper.JqGrid
{
    public class BuildGridDataHelper<T> : IBuildGridDataHelper<T> where T:class 
    {
        private ISortBuilder _sortBuilder;
        private IEntityHelper _entityHelper;

        public BuildGridDataHelper(IEntityHelper entityHelper,
            ISortBuilder sortBuilder)
        {
            _entityHelper = entityHelper;
            _sortBuilder = sortBuilder;
        }

        public string BuildDataForGrid(List<T> sources, Func<T, string[]> generateCellValues,
             string sortName, string sortOrder, int rowId = 0)
        {
            var sortedSource = _sortBuilder.Sort(sources, sortName, sortOrder);
            var numberOfRecords = sortedSource.Count;

            // Create data as format of grid
            var _filter = sortedSource.Select(x => new
            {
                id = _entityHelper.GetKeyValue(x),
                cell = generateCellValues(x)
            }).ToList();

            //Create json data
            var jsonData = new
            {
                records = numberOfRecords,
                rows = _filter
            };

            var java = new JavaScriptSerializer();
            java.MaxJsonLength = Int32.MaxValue;
            return java.Serialize(jsonData);
        }
    }
}